package com.gugee.ins.common.dal.service.blogger.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gugee.ins.common.dal.mapper.blogger.InsRelBloggerFollowerMapper;
import com.gugee.ins.common.dal.service.blogger.InsRelBloggerFollowerDao;
import com.gugee.ins.common.model.mysql.blogger.InsRelBloggerFollower;

import lombok.extern.slf4j.Slf4j;


import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * InsRelBloggerFollowingDao
 * @author Huangxin
 */
@Slf4j
@Service
public class InsRelBloggerFollowerDaoImpl extends ServiceImpl<InsRelBloggerFollowerMapper, InsRelBloggerFollower> implements InsRelBloggerFollowerDao {


    /**
     * 批量插入 博主和粉丝的关联信息
     * @param uid
     * @param insRelBloggerFollowerUid
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchInsertByUid(long uid,List<Long> insRelBloggerFollowerUid) {
        long nowTime = System.currentTimeMillis() / 1000;
        List<InsRelBloggerFollower> insRelBloggerFollowers = new ArrayList<>(insRelBloggerFollowerUid.size());
        for(long followerUid : insRelBloggerFollowerUid){
            InsRelBloggerFollower insRelBloggerFollower = new InsRelBloggerFollower();
            insRelBloggerFollower.setFUid(followerUid);
            insRelBloggerFollower.setUid(uid);
            insRelBloggerFollower.setCreateTime(nowTime);
            insRelBloggerFollowers.add(insRelBloggerFollower);
        }
        try{
            this.saveBatch(insRelBloggerFollowers,insRelBloggerFollowers.size() + 1);
        }catch (Exception e){
            log.debug("batch insert ins blogger follower failed ,try insert one by one, msg : {} ",e.getMessage());
            insRelBloggerFollowers.forEach(insRelBloggerFollower -> {
                try{
                    baseMapper.insert(insRelBloggerFollower);
                }catch (Exception ex){
                    log.info("insert ins blogger follower failed ,uid : {} ,followingUid : {}, msg : {} "
                            ,uid,insRelBloggerFollower.getFUid(),ex.getMessage());
                }
            });
        }
    }

    /**
     * 删除博主和粉丝的关联信息
     * @param uid
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByUid(long uid) {
        Map<String,Object> deleteMap = new HashMap<>(1);
        deleteMap.put("uid",uid);
        baseMapper.deleteByMap(deleteMap);
    }

    @Override
    public int countByUid(long uid) {
        return baseMapper.countRealBlogger(uid);
    }
}
